var app = getApp();
var ux = require('../../../../lib/ux.js');
var QQMapWX = require('../../../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
var animation;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    long: '',
    lan: '',
    showCityPicker: false,
    citytab: 0,
    citytabs: ["请选择"],
    adressList: [],
    cityIndex: -1,
    addressName: '',
    proviceIndex: -1,
    cityIndex: -1,
    countyIndex: -1,
    countryIndex: -1,
    provice: null,
    city: null,
    county: null,
    country: null,
    tab: 0,
    agentConf: {},
    partnerConfig: {},
    agent: null,
    HHR: null,
    authModle: false,
    userId: null,
    userInfo: {},
    animationAddressMenu: {},
    addressMenuIsShow: false,
    thisType: 0,
    pidUrl: "/api/address/pidAdderssList.do",
    youshi: "",
    mobile: "",
    name: "",
    profile: "",
    focus: false,
    action: "/api/memberAgent/HHRSave.do",
    submit: "{{submit}}",
    agentUrls: "/api/memberUser/getApplyPageData.do"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    qqmapsdk = new QQMapWX({
      key: 'B5WBZ-NBAHJ-MJQFY-F4RWO-MPNOV-NNBQC' //这里自己的key秘钥进行填充
    });
    wx.hideShareMenu();
    if (options.pa){
      this.setData({
        tab:options.tab?options.tab:'',
        long: JSON.parse(options.pa).long,
        lan: JSON.parse(options.pa).lan
      })
    }
    if (options.id) {
      this.setData({
        id: options.id
      })
    } else if (options.userId) {
      this.setData({
        tab:options.tab,
        id: options.banrdId,
        userId: options.userId
      })
    } else {
      this.setData({
        setting: wx.getStorageSync("setting"),
        userInfo: wx.getStorageSync("userInfo"),
        id: wx.getStorageSync("banrdId")
      })
    }
    // 初始化动画变量
    var animation = wx.createAnimation({
      duration: 800,
      transformOrigin: "50% 50%",
      timingFunction: 'ease',
    })
    this.animation = animation;
    var self = this;
    if (options.userId) {
      var parmasaa = {
        merchant: options.banrdId,
        memberId: options.userId
      }
      ux.redLogin(parmasaa, function (protocol) {
        if (protocol.data.type == 1) {//已授权
          self.setData({
            userInfo: protocol.data.userInfo
          })
          var pp = { banrdId: self.data.id };
          ux.request(self.data.agentUrls, pp, function (protocol) {
            var adressList = self.data.adressList;
            adressList[self.data.citytab] = protocol.data.alist
            self.setData({
              adressList: adressList,
              agentConf: protocol.data.agentConf,
              partnerConfig: protocol.data.partnerConfig,
              agent: protocol.data.agent,
              HHR: protocol.data.HHR,
              parameter: protocol.data.parameter
            })
          }, true);
        } else if (protocol.data.type == 2) {//未授权
          self.setData({
            authModle: true,
          })
        }
      })
    } else {
      var pp = { banrdId: self.data.id };
      ux.request(self.data.agentUrls, pp, function (protocol) {
        var adressList = self.data.adressList;
        adressList[self.data.citytab] = protocol.data.alist
        self.setData({
          adressList: adressList,
          agentConf: protocol.data.agentConf,
          partnerConfig: protocol.data.partnerConfig,
          agent: protocol.data.agent,
          HHR: protocol.data.HHR,
          parameter: protocol.data.parameter
        })
      }, true);
      ux.login(function (protocol) {
        if (protocol.success) {
          wx.setStorageSync("userInfo", protocol.data.userInfo);
          wx.setStorageSync("token", protocol.data.token);
          self.setData({
            userInfo: protocol.data.userInfo
          })
        }
      });
    }

  },
  getParameter: function () {
    var self = this;
    var parmas = { id: parseInt(self.data.id) }
    ux.request(self.data.parameterUrl, parmas, function (protocol2) {
      self.setData({
        parameter: protocol2.data.pam
      });
      wx.setStorageSync("parameter", protocol2.data.pam);
    }, true);
  },
  getUserInfoFun: function (e) {
    var self = this;
    var userInfo = e.detail.userInfo
    var params = {};
    params.nickname = userInfo.nickName;
    params.header = userInfo.avatarUrl;
    params.sex = userInfo.gender;
    wx.showLoading({
      mask: true,
      title: '处理中....',
    })
    wx.login({
      success: function (res) {
        if (res.code) {
          params.jscode = res.code;
          ux.request("/api/member/registerUser.do", params,
            function (protocol) {
              if (protocol.success) {
                wx.setStorageSync("userInfo", protocol.data.userInfo);
                wx.setStorageSync("token", protocol.data.token);
                wx.setStorageSync("setting", protocol.data.setting);
                wx.hideLoading();
                self.setData({
                  setting: wx.getStorageSync("setting"),
                  userInfo: protocol.data.userInfo,
                  authModle: false,
                })
                var pp = { banrdId: self.data.id };
                ux.request(self.data.agentUrls, pp, function (protocol) {
                  self.setData({
                    agentType: protocol.data.agentType,
                    agent: protocol.data.agent
                  })
                }, true);
              } else {
                wx.hideLoading();
                wx.showToast({
                  title: '系统繁忙!',
                })
              }
            }, true);
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      },
      complete: function (res) {
        console.log(JSON.stringify(res))
      }
    })
  },
  preventTouchMoveTy: function () {
    return;
  },
  onForm: function (event) {
    if (this.data.submit) {
      var $this = this;
      var dataset = event.currentTarget.dataset;
      ux.request(this.data.submit, detail.value, function (protocol) {
        if (protocol.success) {
          if (dataset.url) {
            wx.redirectTo(dataset.url);
          }
        }
      }, true);
    }
  },

  onTap: function (event) {
    var dataset = event.currentTarget.dataset;
    var data = this.data;
    if (dataset.key && dataset.val) {
      data[dataset.key] = dataset.val;
    }
    this.setData(data);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var self = this;
    wx.showShareMenu({
      withShareTicket: true
    })
    var shareObj = {
      title: wx.getStorageSync("setting").coverTitle,
      imageUrl: wx.getStorageSync("setting").coverImg,
      path: '/pages/brandSelect?otherId=' + wx.getStorageSync("userInfo").uid,
      success: function (res) {
      },
      fail: function () {
        wx.showToast({
          title: '转发失败',
        })
      }
    }
    return shareObj;
  },
  liji: function () {
    this.setData({
      focus: true
    })
  },
  mobiles: function (e) {
    this.setData({
      mobile: e.detail.value
    })
  }, profiles: function (e) {
    this.setData({
      profile: e.detail.value
    })
  },
  names: function (e) {
    this.setData({
      name: e.detail.value
    })
  },
  youshis: function (e) {
    this.setData({
      youshi: e.detail.value
    })
  },
  /**城市 开始*/

  getAddressList: function (pid) {
    var self = this;
    var params = { pid: pid };
    wx.showLoading({
      mask: true,
      title: '正在加载...'
    })
    ux.request('/api/address/getAddressListByPidSub.do', params, function (data) {
      wx.hideLoading();
      var adressList = self.data.adressList;
      adressList[self.data.citytab] = data.data.list
      self.setData({
        adressList: adressList
      })
    }, true);
  },
  showCityPicker: function () {
    this.setData({
      showCityPicker: true,
      hosList: []
    })
  },
  tabClick: function (event) {
    var dataset = event.currentTarget.dataset;
    var index = dataset.index;
    this.setData({
      citytab: index
    })
    if (index == 0) {
      this.setData({
        selectsIndex: this.data.proviceIndex,
      })
    } else if (index == 1) {
      this.setData({
        selectsIndex: this.data.cityIndex,
      })
    } else if (index == 2) {
      this.setData({
        selectsIndex: this.data.countyIndex,
      })
    } else if (index == 3) {
      this.setData({
        selectsIndex: this.data.countryIndex,
      })
    }
  },
  selectThis: function (event) {
    var dataset = event.currentTarget.dataset;
    var idx = dataset.idx;
    var index = dataset.index;
    console.log(idx);
    var adressList = this.data.adressList;
    var tabs = this.data.citytabs;
    var id = adressList[idx][index].id;
    var tabName = adressList[idx][index].name;
    var newTabs = []
    var newList = []
    var idxtab = 0;

    if (idx == 0) {
      this.setData({
        provice: id,
        proviceIndex: index,
        city: null,
        county: null,
        country: null,
        cityIndex: -1,
        countyIndex: -1,
        countryIndex: -1,
      })
    } else if (idx == 1) {
      this.setData({
        city: id,
        county: null,
        country: null,
        cityIndex: index,
        countyIndex: -1,
        countryIndex: -1,
      })
    } else if (idx == 2) {
      this.setData({
        county: id,
        country: null,
        countyIndex: index,
        countryIndex: -1,
      })
    } else if (idx == 3) {
      this.setData({
        country: id,
        countryIndex: index,
      })
    }
    if (idx < 4) {
      for (var i = 0; i < tabs.length; i++) {
        newList[i] = adressList[i]
        if (i == idx) {
          newTabs[i] = tabName
          if (idx == 3) {
            idxtab = idx
            break;
          } else {
            newTabs.push("请选择");
            idxtab = idx + 1
            break;
          }
        } else {
          idxtab = idx;
          newTabs[i] = tabs[i]
        }
      }
      this.setData({
        adressList: newList,
        citytabs: newTabs,
        citytab: idxtab
      })
      if (idx != 3) {
        this.getAddressList(adressList[idx][index].id);
      } else {
        this.setData({
          selectsIndex: this.data.countryIndex,
        })
        this.okCityClick();
      }
    }
  },
  okCityClick: function () {
    var ps = '';
    var lists = this.data.adressList;

    if (this.data.proviceIndex >= 0) {
      ps = ps + lists[0][this.data.proviceIndex].name + ">";
    }
    if (this.data.cityIndex >= 0) {
      ps = ps + lists[1][this.data.cityIndex].name + ">";
    }
    if (this.data.countyIndex >= 0) {
      ps = ps + lists[2][this.data.countyIndex].name + ">";
    }
    if (this.data.countryIndex >= 0) {
      ps = ps + lists[3][this.data.countryIndex].name + ">";
    }
    this.setData({
      addressName: ps.substring(0, ps.length - 1),
      showCityPicker: false
    })
  },
  /**城市 结束*/
  toast: function (params) {
    if (typeof (params) == "string") {
      params = { content: params };
    }
    this.setData({
      toast: params.content
    });
    var THIS = this;
    setTimeout(function () {
      THIS.setData({
        toast: false
      });
      if (params.complete) {
        params.complete();
      }
    }, params.time || 3000);
  },
  tijiao: function () {
    var self = this;
    if (!this.data.name) {
      this.toast("请输入联系人");
      return false;
    }
    if (!this.data.mobile) {
      this.toast("请输入联系电话");
      return false;
    }
    var regMobile = /^1\d{10}$/;
    if (!regMobile.test(this.data.mobile)) {
      this.toast("手机格式有误");
      return false;
    }
    if (!this.data.country) {
      this.toast("请选择所在城市");
      return false;
    }
    if (!this.data.profile) {
      this.toast("请介绍下自己");
      return false;
    }
    if (!this.data.youshi) {
      this.toast("请说说您的优势");
      return false;
    }
    var pamars = {
      longitude: this.data.long,
      latitude: this.data.lan,
      name: this.data.name,
      mobile: this.data.mobile,
      profile: this.data.profile,
      youshi: this.data.youshi,
      banrdId: this.data.id,
      adressId: this.data.country
    }
    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    ux.request(this.data.action, pamars, function (protocol) {
      wx.hideLoading();
      if (protocol.data.type == 1) {
        self.toast("提交成功");
        self.setData({
          HHR: protocol.data.HHR
        })
      } else {
        self.toast("系统错误");
      }
    }, true)
  },
  notClick: function () {
    this.toast("当前街道已有合伙人...请选择其他街道");
  },
  qugouHhr: function () {
      wx.navigateTo({
        url: '/pages/member/tab1/agent/hhrCard?long=' + wx.getStorageSync("longitude") + '&lan=' + wx.getStorageSync("latitude") + '&banrdId=' + this.data.id,
      })
  },
  qugou: function () {
    wx.navigateTo({
      url: '/pages/member/tab1/agent/cardPay?banrdId=' + this.data.id,
    })
  },
  toOne: function () {
    this.setData({
      tab: 0
    })
  },
  toTow: function () {
    this.setData({
      tab: 1
    })
  },
  gotoSelect: function () {
    wx.reLaunch({
      url: '/pages/member/tab1/sugarSpice?id='+this.data.id,
    })
  },
  getUserLocation: function () {
    wx.showLoading({
      title: '加载中...',
    })
    let vm = this;
    wx.getSetting({
      success: (res) => {
        wx.hideLoading();
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {

          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      vm.getLocation();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          vm.getLocation();
        }
        else {
          //调用wx.getLocation的API
          vm.getLocation();
        }
      }
    })
  },

  // 微信获得经纬度
  getLocation: function () {
    let vm = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy;
        vm.getLocal(latitude, longitude)
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res))
      }
    })
  },
  // 获取当前地理位置
  getLocal: function (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        let province = res.result.ad_info.province;
        let city = res.result.ad_info.city;
        let district = res.result.ad_info.district;
        console.log(JSON.stringify(res.result.ad_info))
        vm.setData({
          province: province,
          city: city,
          lan: latitude,
          long: longitude,
          district: district
        })
        setTimeout(function () {
          wx.hideLoading();
        }, 3000);

      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  }
})
